<template>
  <div class="user-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片面板 -->
    <el-card class="box-card">
      <div style="margin-top: 15px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input placeholder="请输入内容" v-model="userObj.query" class="iptBox">
              <el-button slot="append" icon="el-icon-search" @click="searchData"></el-button>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="addUser">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column type="index" width="50" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#dcdfe6"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <!-- 操作按钮 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="dataEdit(scope.row)" icon="el-icon-edit"></el-button>
            <el-button
              size="mini"
              type="danger"
              @click="dataDelete(scope.row.id)"
              icon="el-icon-delete"
              slot="reference"
            ></el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="handleRoles(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userObj.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userObj.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total1"
      ></el-pagination>
    </el-card>
    <!-- 编辑页面 -->
    <el-dialog title="修改用户" :visible.sync="dialogFormVisible">
      <el-form :model="formEdit" :rules="rulesEdit" ref="formEditDialog">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="formEdit.username" :disabled="true" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="formEdit.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="formEdit.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="aaa">取 消</el-button>
        <el-button type="primary" @click="editButton">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加页面 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible1">
      <el-form :model="formAdd" :rules="rulesAdd" ref="formAddDialog">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="formAdd.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="formAdd.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="formAdd.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="formAdd.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="addButton">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色页面 -->
    <el-dialog title="分配角色" :visible.sync="dialogFormVisibleRoles">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="当前的用户：">{{objRoles.username}}</el-form-item>
        <el-form-item label="当前的角色：">{{objRoles.role_name}}</el-form-item>
        <el-form-item label="分配新角色：">
          <el-select v-model="form.rid" placeholder="请选择活动区域" >
            <el-option
              v-for="(item,index) in  roleList"
              :key="index"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleRoles = false">取 消</el-button>
        <el-button type="primary" @click="rolesFormSet">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
           
<script>
import { users_api } from "@/api";
import { userPut_api } from "@/api";
import { edituserPut_api } from "@/api";
import { deluserPut_api } from "@/api";
import { adduser_api,roles_api,rolesSet_api } from "@/api";

export default {
  data() {
    return {
      //控制编辑的显示
      dialogFormVisible: false,
      //控制添加的显示
      dialogFormVisible1: false,
      //控制分配角色的显示
      dialogFormVisibleRoles: false,
      //编辑表单的数据
      formEdit: {},
      rulesEdit: {
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
      //添加表单的数据
      formAdd: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      rulesAdd: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
      formLabelWidth: "120px",
      //表格数据
      tableData: [],

      // 数据总数
      total1: 0,

      /* 获取数据列表参数对象 */
      userObj: {
        query: "",
        // 当前页码
        pagenum: 1,
        // 每页的数据
        pagesize: 10,
      },
      //分配角色
      form: {
        rid: "",
        id: JSON.parse(window.sessionStorage.getItem("user")).id,
      },
      objRoles: {},
      roleList: [],
    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    /* 分页组件提供的事件 */
    handleSizeChange(val) {
      // console.log(val,111);
      //val表示每页多少条
      this.userObj.pagesize = val;
      this.getUsers();
    },
    handleCurrentChange(val) {
      // val表示当前的页码
      this.userObj.pagenum = val;
      this.getUsers();
      // console.log(val,222);
    },
    //搜索功能
    searchData() {
      this.getUsers();
    },
    //添加用户
    addUser() {
      //显示添加表单
      this.dialogFormVisible1 = true;
    },
    //添加表单
    addButton() {
      // 进行二次校验
      this.$refs.formAddDialog.validate(async (valid) => {
        if (valid) {
          //发送请求进行用户添加
          const { data: res } = await adduser_api(this.formAdd);
          // console.log(res);
          //判断请求是否成功
          if (res.meta.status === 201) {
            this.$message({
              showClose: true,
              message: res.meta.msg,
              type: "success",
            });
          } else {
            this.$message({
              showClose: true,
              message: res.meta.msg,
              type: "success",
            });
          }
          //清空表单数据
          this.$refs.formAddDialog.resetFields();
          //关闭编辑表单
          this.dialogFormVisible1 = false;
          //刷新数据
          this.getUsers();
        } else {
          return false;
        }
      });
    },
    //操作中的按钮
    // 编辑按钮
    dataEdit(row) {
      //显示编辑表单
      this.dialogFormVisible = true;
      //把当前行数据赋值给表单
      // console.log(row);
      this.formEdit = row;
    },
    aaa() {
      this.dialogFormVisible = false;
      this.getUsers();
    },
    //编辑表单
    editButton() {
      // 进行二次校验
      this.$refs.formEditDialog.validate(async (valid) => {
        if (valid) {
          //发送请求进行用户修改
          const { data: res } = await edituserPut_api(this.formEdit);
          // console.log(res);
          //判断请求是否成功
          if (res.meta.status === 200) {
            this.$message({
              showClose: true,
              message: res.meta.msg,
              type: "success",
            });
          } else {
            this.$message({
              showClose: true,
              message: res.meta.msg,
              type: "success",
            });
          }
          //关闭编辑表单
          this.dialogFormVisible = false;
        } else {
          return false;
        }
      });
    },
    // 删除
    dataDelete(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //发送请求
          const { data: res } = await deluserPut_api(id);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          //更新数据
          this.getUsers();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改用户状态
    async userStateChanged(row) {
      //发送请求进行状态修改
      const { data: res } = await userPut_api(row.id, row.mg_state);
      console.log(res);
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) {
        return this.$message.error("修改状态失败");
      }
      this.$message.success("更新状态成功");
    },
     /* 分配角色===获取所有的角色 */
    async handleRoles(row) {
      this.dialogFormVisibleRoles = true
      this.objRoles = row
      // console.log(this.objRoles, 666666)
      
      const { data: res } = await roles_api()
      this.roleList = res.data
      // console.log(res.data);
    },
    //  分配角色
    async rolesFormSet() {
      const { data: res } = await rolesSet_api(this.form)
      // console.log(this.form);
      // console.log(res, 4455)
       this.dialogFormVisibleRoles = false
      this.getUsers()
    },
    /* 获取用户数据列表 */
    async getUsers() {
      const { data: res } = await users_api(this.userObj);
      // console.log(res, 888);
      //  将获取的用户数据赋值给tableData
      this.tableData = res.data.users;
      //把数据总数给total1
      this.total1 = res.data.total;
    },
  },
};
</script>
<style scoped lang="less">
.user-container {
  .el-breadcrumb {
    margin-bottom: 20px;
  }
}
</style>